package com.sgcc.sx.pmos.e_sx_mall.fragment;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgcc.sx.pmos.arouter.mall.MallArouterPath;
import com.sgcc.sx.pmos.arouter.personalcenter.PersonalCenterArouterPath;
import com.sgcc.sx.pmos.common.base.MvpBaseFragment;
import com.sgcc.sx.pmos.common.bean.BaseResponse;
import com.sgcc.sx.pmos.common.bean.EventCenter;
import com.sgcc.sx.pmos.common.bean.GoodScreenBackBean;
import com.sgcc.sx.pmos.common.bean.PackageBean;
import com.sgcc.sx.pmos.common.bean.RatioCurveBean;
import com.sgcc.sx.pmos.common.dialog.GoodScreenDialog;
import com.sgcc.sx.pmos.common.dialog.OnSearchClickListener;
import com.sgcc.sx.pmos.common.http.HttpInterConst;
import com.sgcc.sx.pmos.common.http.HttpRequestUtils;
import com.sgcc.sx.pmos.common.http.MvcNetCallback;
import com.sgcc.sx.pmos.common.utils.ArguConstant;
import com.sgcc.sx.pmos.common.utils.ListPageUtil;
import com.sgcc.sx.pmos.common.utils.SmartLoadUtil;
import com.sgcc.sx.pmos.common.utils.UserManager;
import com.sgcc.ln.pmos.common.widget.LoadingLayout;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.sx.pmos.e_sx_mall.adapter.GoodsAdapter;
import com.sgcc.sx.pmos.e_sx_mall.adapter.GoodsTwoLinAdapter;
import com.sgcc.sx.pmos.e_sx_mall.bean.MallGoodsBean;
import com.sgcc.sx.pmos.e_sx_mall.contract.GoodsContract;
import com.sgcc.sx.pmos.e_sx_mall.dialog.GoodsSortPop;
import com.sgcc.sx.pmos.e_sx_mall.presenter.GoodsPresenter;
import com.sgcc.sx.pmos.mobileapp.dialog.AccountIncrementPopup;
import com.sgcc.sx.pmos.mobileapp.dialog.ChartLinSelectPop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品
 */
public class GoodsFragment extends MvpBaseFragment<GoodsPresenter> implements GoodsContract.View, LoadingLayout.RetryListener {

    private LinearLayout mLlScreening;
    private SmartRefreshLayout mRefreshLayout;
    private LoadingLayout mLoadinglayout;
    private RecyclerView mRecycleview;
    private ImageButton mIbPk;
    private ImageButton mIbMycollection;
    private ImageButton mIbInvitation;
    private ImageView typeSwitchiImg;
    public BaseQuickAdapter adapter;
    public GoodsAdapter mGoodsAdapter;
    public GoodsTwoLinAdapter mGoodsTwoLinAdapter;
    public boolean isrefresh = false;//是否是刷新状态
    public List<PackageBean> mData = new ArrayList<>();
    private boolean showSingleLine = true;//展示模式 单行双行
    private GoodScreenDialog goodScreenDialog;
    private RelativeLayout rl_goods_left;
    //    private RelativeLayout rl_goods_center;
    private RelativeLayout rl_goods_right;

    private TextView tx_goods_left;
    //    private TextView tx_goods_center;
    private TextView tx_goods_right;

    private ImageView xsdl_up_img;
    private ImageView xsdl_down_img;

//    private ImageView ygjj_up_img;
//    private ImageView ygjj_down_img;

    private ImageView sjsj_up_img;
    private ImageView sjsj_down_img;

    private LinearLayout header_layout;
    private LinearLayout linner_goods_right;
    int SortState = 0;
    int SortPosition = 0;
    GoodScreenBackBean goodScreenBackBean;
    String soldEnergySort = "";
    String avgPriceSort = "";
    String createDateSort = "";
    String[] selectList = {"默认随机排序", "销售电量升序", "销售电量降序", "预估价格升序", "预估价格降序", "上架时间升序", "上架时间降序"};
    String ratioId = "1", ratioName;

    int chartposition = 0;
    ChartLinSelectPop pop;
    GoodsSortPop orderPop;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_goods;
    }

    @Override
    protected GoodsPresenter createPresenter() {
        return new GoodsPresenter();
    }

    @Override
    protected void initViews() {
        super.initViews();
//        ratioId = SPUtils.getInstance().getString("ratioId", "1");
//        ratioName = SPUtils.getInstance().getString("ratioName", "");
        findViewByIds();
        getChartList();
    }

    private void findViewByIds() {
        mLlScreening = mRootView.findViewById(R.id.ll_screening);
        mRefreshLayout = mRootView.findViewById(R.id.refreshLayout);
        mLoadinglayout = mRootView.findViewById(R.id.loadinglayout);
        mRecycleview = mRootView.findViewById(R.id.recycleview);
        mIbPk = mRootView.findViewById(R.id.ib_pk);
        mIbInvitation = mRootView.findViewById(R.id.ib_invitation);
        mIbMycollection = mRootView.findViewById(R.id.ib_mycollection);
        mIbInvitation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserManager.toLogin()) {
                    ARouter.getInstance()
                            .build(MallArouterPath.MALL_INVITATIONLIST)
                            .navigation();
                }
            }
        });
        header_layout = mRootView.findViewById(R.id.header_layout);
        rl_goods_left = mRootView.findViewById(R.id.rl_goods_left);
        rl_goods_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                setLeftSortUI();
                showOrderByPop();
//                refresh(true);

            }
        });
//        rl_goods_center = mRootView.findViewById(R.id.rl_goods_center);
//        rl_goods_center.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                setCenterSortUI();
//                refresh(true);
//            }
//        });
        rl_goods_right = mRootView.findViewById(R.id.rl_goods_right);
        rl_goods_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                setRightSortUI();
                showChartByPop();
//                refresh(true);
            }
        });
        tx_goods_left = mRootView.findViewById(R.id.tx_goods_left);
//        tx_goods_center = mRootView.findViewById(R.id.tx_goods_center);
        tx_goods_right = mRootView.findViewById(R.id.tx_goods_right);

        xsdl_up_img = mRootView.findViewById(R.id.xsdl_up_img);
        xsdl_down_img = mRootView.findViewById(R.id.xsdl_down_img);


        rl_goods_left = mRootView.findViewById(R.id.rl_goods_left);
        rl_goods_left = mRootView.findViewById(R.id.rl_goods_left);

//        ygjj_up_img = mRootView.findViewById(R.id.ygjj_up_img);
//        ygjj_down_img = mRootView.findViewById(R.id.ygjj_down_img);

        sjsj_up_img = mRootView.findViewById(R.id.sjsj_up_img);
        sjsj_down_img = mRootView.findViewById(R.id.sjsj_down_img);


        typeSwitchiImg = mRootView.findViewById(R.id.type_switch_img);
        typeSwitchiImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSingleLine = !showSingleLine;
                adapter = getAdapter(showSingleLine);
                if (!showSingleLine) {
                    typeSwitchiImg.setBackgroundResource(R.mipmap.mall_changed);
                    mRecycleview.setLayoutManager(new GridLayoutManager(getContext(), 2));
                } else {
                    typeSwitchiImg.setBackgroundResource(R.mipmap.mall_change);
                    mRecycleview.setLayoutManager(new GridLayoutManager(getContext(), 1));
                }
                mRecycleview.setAdapter(adapter);
                refresh(true);
            }
        });
        adapter = getAdapter(true);
        if (adapter != null) {
            mRecycleview.setAdapter(adapter);
        }
        mLoadinglayout.showContent();
        mLoadinglayout.setRetryListener(this);
        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh(false);
            }
        });

        mIbPk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(UserManager.toLogin()){
                    //套餐对比
                    ARouter.getInstance()
                            .build(MallArouterPath.MALL_COMPARISONLIST)
                            .navigation();
                }

            }
        });
        mIbMycollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //我的收藏
                if (UserManager.toLogin()) {
                    ARouter.getInstance()
                            .build(PersonalCenterArouterPath.PERSONALCENTER_COLLECTION)
                            .navigation();
                }
            }
        });
        mLlScreening.setOnClickListener(view -> {

            if (null == goodScreenDialog)
                goodScreenDialog = (GoodScreenDialog) new XPopup.Builder(getContext())
                        .popupPosition(PopupPosition.Right)//右边
                        .hasStatusBarShadow(true) //启用状态栏阴影
                        .asCustom(new GoodScreenDialog(getContext(), goodScreenBackBean, new OnSearchClickListener<GoodScreenBackBean>() {
                            @Override
                            public void onClick(GoodScreenBackBean goodScreenBackBean) {
                                GoodsFragment.this.goodScreenBackBean = goodScreenBackBean;
                                refresh(true);
                            }
                        })).show();
            else
                goodScreenDialog.show();
        });
        tx_goods_right.setText(ratioName);

    }

    public BaseQuickAdapter getAdapter(boolean showSingleLine) {
        if (showSingleLine) {
            mGoodsAdapter = new GoodsAdapter(mContext);
            mGoodsAdapter.setItemClickListener(new GoodsAdapter.OnItemClickListener() {
                @Override
                public void OnAddCollectionListener(int position, PackageBean bean) {
                    if (UserManager.toLogin()) {
                        mPresenter.addUserPackageCollection("", bean.getMembersSdId(), bean.getMembersSdName(),
                                bean.getCombId(), bean.getCombName());
                    }
                }

                @Override
                public void OnCancleCollectionListener(int position, PackageBean bean) {
                    mPresenter.deletePackageById(bean.getCombId(), bean.getMembersSdId());
                }

                @Override
                public void OnItemsClickListener(int position, PackageBean bean) {
                    ARouter.getInstance()
                            .build(MallArouterPath.MALL_PACKAGEDETAILS)
                            .withString("combName", bean.getCombCode())
                            .withBoolean("isBlue", "1".equals(bean.getpNum()) && ("03".equals(bean.getMainType()) || "04".equals(bean.getMainType())) &&
                                    "0".equals(bean.getMainItemType()) &&
                                    ("0".equals(bean.getMainDifType()) || TextUtils.isEmpty(bean.getMainDifType())))
                            .navigation();
                }
            });
            return mGoodsAdapter;
        } else {
            mGoodsTwoLinAdapter = new GoodsTwoLinAdapter(mContext);
            mGoodsTwoLinAdapter.setItemClickListener(new GoodsTwoLinAdapter.OnItemClickListener() {
                @Override
                public void OnAddCollectionListener(int position, PackageBean bean) {
                    if (UserManager.toLogin()) {
                        mPresenter.addUserPackageCollection("", bean.getMembersSdId(), bean.getMembersSdName(),
                                bean.getCombId(), bean.getCombName());
                    }
                }

                @Override
                public void OnCancleCollectionListener(int position, PackageBean bean) {
                    mPresenter.deletePackageById(bean.getCombId(), bean.getMembersSdId());
                }

                @Override
                public void OnItemsClickListener(int position, PackageBean bean) {
                    ARouter.getInstance()
                            .build(MallArouterPath.MALL_PACKAGEDETAILS)
                            .withString("combName", bean.getCombCode())
                            .withBoolean("isBlue", "1".equals(bean.getpNum()) && ("03".equals(bean.getMainType()) || "04".equals(bean.getMainType())) &&
                                    "0".equals(bean.getMainItemType()) &&
                                    ("0".equals(bean.getMainDifType()) || TextUtils.isEmpty(bean.getMainDifType())))
                            .navigation();
                }
            });
            return mGoodsTwoLinAdapter;
        }
    }

    @Override
    public boolean isBindEventBusHere() {
        return true;
    }

    @Override
    public void onEventMainThread(EventCenter eventCenter) {
        super.onEventMainThread(eventCenter);
        if (eventCenter.getEventCode() == ArguConstant.SELECT_CURVE_BACK) {
            if (null != goodScreenDialog) {
                RatioCurveBean.Bean bean = (RatioCurveBean.Bean) eventCenter.getData();
                goodScreenDialog.setText(bean);
            }
        }
        if (eventCenter.getEventCode() == ArguConstant.REFRESH_CONTRAST) {
            mGoodsAdapter.notifyDataSetChanged();
        }
        if (eventCenter.getEventCode() == ArguConstant.REFRESH_GOODS_LIST) {
            refresh(true);
        }

    }

    public void refresh(boolean isloading) {
        isrefresh = true;
        getDataRequest(0, isloading);
    }

    private void loadMore() {
        isrefresh = false;
        getDataRequest(mData.size(), false);
    }

    int mListSize;

    public void getDataRequest(int listSize, boolean isloading) {
        mListSize = listSize;

        mPresenter.getGoodsList(listSize, isloading, ratioId, soldEnergySort, avgPriceSort, createDateSort, goodScreenBackBean);
    }

    @Override
    public void onErrorclick() {
        refresh(true);
    }

    /**
     * @author yinsh
     * @description 请求成功
     * @date 2021/8/19 上午10:53
     */
    public void loadSuccess(boolean hasNext, List<PackageBean> datas) {
        if (isrefresh) {
            mData.clear();
        }
        if (datas != null) {
            mData.addAll(datas);
        }

        adapter.setNewData(mData);
        adapter.notifyDataSetChanged();
        SmartLoadUtil.canLoadMore(mData, hasNext, mRefreshLayout, mLoadinglayout, isrefresh, false);
    }

    /**
     * @author yinsh
     * @description 请求成功
     * @date 2021/8/19 上午10:52
     */
    public void loadFalied() {
        SmartLoadUtil.canFailLoadMore(mRefreshLayout, mLoadinglayout, isrefresh, false);
    }


    @Override
    public void queryGoodsListSuccess(MallGoodsBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                if (response.getData() != null) {
                    loadSuccess(ListPageUtil.isHasNextPage(response.getData().getTotal(), mListSize), response.getData().getData());
                }
            } else {
                loadFalied();
            }
        }
    }

    @Override
    public void queryGoodsListFailed() {
        loadSuccess(false, new ArrayList<>());
//        loadFalied();
    }

    @Override
    public void addCollectionSuccess(BaseResponse response, String combId) {
        if (response != null) {
            if (response.isSuccess()) {
                List<PackageBean> list = mGoodsAdapter.getData();
                int index = 0;
                for (int i = 0; i < list.size(); i++) {
                    if (combId.equals(list.get(i).getCombId())) {
                        list.get(i).setUstatus("01");
                        index = i;
                    }
                }
                mGoodsAdapter.notifyItemChanged(index);
                if (mGoodsTwoLinAdapter != null) {
                    mGoodsTwoLinAdapter.notifyItemChanged(index);
                }

            }
        }
    }

    @Override
    public void deletePackageByIdSuccess(BaseResponse response, String combId) {
        if (response != null) {
            if (response.isSuccess()) {
                List<PackageBean> list = mGoodsAdapter.getData();
                int index = 0;
                for (int i = 0; i < list.size(); i++) {
                    if (combId.equals(list.get(i).getCombId())) {
                        list.get(i).setUstatus("00");
                        index = i;
                    }
                }
                mGoodsAdapter.notifyItemChanged(index);
                if (mGoodsTwoLinAdapter != null) {
                    mGoodsTwoLinAdapter.notifyItemChanged(index);
                }

            }
        }
    }

    @Override
    public void addCollectionFailed() {

    }

//    private void initSortUI() {
//        tx_goods_left.setTextColor(0xff999999);
//        tx_goods_center.setTextColor(0xff999999);
//        tx_goods_right.setTextColor(0xff999999);
//
//        xsdl_up_img.setBackgroundResource(R.mipmap.mall_top_store_b_up);
//        xsdl_down_img.setBackgroundResource(R.mipmap.mall_top_store_b);
//
//        ygjj_up_img.setBackgroundResource(R.mipmap.mall_top_store_b_up);
//        ygjj_down_img.setBackgroundResource(R.mipmap.mall_top_store_b);
//
//        sjsj_up_img.setBackgroundResource(R.mipmap.mall_top_store_b_up);
//        sjsj_down_img.setBackgroundResource(R.mipmap.mall_top_store_b);
//
//    }

//    private void setLeftSortUI() {
//        if (SortPosition != 1) {
//            SortState = 1;
//        } else {
//            sortStatadd();
//        }
//        initSortUI();
//        if (SortState == 1) {
//            tx_goods_left.setTextColor(0xff3274F0);
//            xsdl_up_img.setBackgroundResource(R.mipmap.mall_top_store_b_up_pre);
//            soldEnergySort = "1";
//            avgPriceSort = "";
//            createDateSort = "";
//        } else if (SortState == 2) {
//            tx_goods_left.setTextColor(0xff3274F0);
//            xsdl_down_img.setBackgroundResource(R.mipmap.mall_top_store_b_pre);
//            soldEnergySort = "0";
//            avgPriceSort = "";
//            createDateSort = "";
//        } else {
//            soldEnergySort = "";
//            avgPriceSort = "";
//            createDateSort = "";
//        }
//        SortPosition = 1;
//    }

//    private void setCenterSortUI() {
//        if (SortPosition != 2) {
//            SortState = 1;
//        } else {
//            sortStatadd();
//        }
//        initSortUI();
//
//        if (SortState == 1) {
//            tx_goods_center.setTextColor(0xff3274F0);
//            ygjj_up_img.setBackgroundResource(R.mipmap.mall_top_store_b_up_pre);
//            soldEnergySort = "";
//            avgPriceSort = "1";
//            createDateSort = "";
//        } else if (SortState == 2) {
//            tx_goods_center.setTextColor(0xff3274F0);
//            ygjj_down_img.setBackgroundResource(R.mipmap.mall_top_store_b_pre);
//            soldEnergySort = "";
//            avgPriceSort = "0";
//            createDateSort = "";
//        } else {
//            soldEnergySort = "";
//            avgPriceSort = "";
//            createDateSort = "";
//        }
//        SortPosition = 2;
//    }

//    private void setRightSortUI() {
//        if (SortPosition != 3) {
//            SortState = 1;
//        } else {
//            sortStatadd();
//        }
//        initSortUI();
//        if (SortState == 1) {
//            tx_goods_right.setTextColor(0xff3274F0);
//            sjsj_up_img.setBackgroundResource(R.mipmap.mall_top_store_b_up_pre);
//            soldEnergySort = "";
//            avgPriceSort = "";
//            createDateSort = "1";
//        } else if (SortState == 2) {
//            tx_goods_right.setTextColor(0xff3274F0);
//            sjsj_down_img.setBackgroundResource(R.mipmap.mall_top_store_b_pre);
//            soldEnergySort = "";
//            avgPriceSort = "";
//            createDateSort = "0";
//        } else {
//            soldEnergySort = "";
//            avgPriceSort = "";
//            createDateSort = "";
//        }
//
//        SortPosition = 3;
//    }

//    private void sortStatadd() {
//        if (SortState < 2) {
//            SortState++;
//        } else {
//            SortState = 0;
//        }
//    }

    private void showOrderByPop() {
        if (orderPop == null) {
            orderPop = (GoodsSortPop) new XPopup.Builder(getContext())
                    .hasShadowBg(true).popupWidth(header_layout.getWidth())
                    .popupAnimation(PopupAnimation.NoAnimation)
                    .atView(header_layout)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                    .asCustom(new GoodsSortPop(getContext(), new GoodsSortPop.OnClickListener() {
                        @Override
                        public void onClick(int position, String text) {

                            tx_goods_left.setText(text);
                            tx_goods_left.setTextColor(0xff3274F0);
                            switch (position) {
                                case 0:
                                    soldEnergySort = "";
                                    avgPriceSort = "";
                                    createDateSort = "";
                                    break;
                                case 1:
                                    soldEnergySort = "1";
                                    avgPriceSort = "";
                                    createDateSort = "";
                                    break;
                                case 2:
                                    soldEnergySort = "0";
                                    avgPriceSort = "";
                                    createDateSort = "";
                                    break;
                                case 3:
                                    soldEnergySort = "";
                                    avgPriceSort = "1";
                                    createDateSort = "";
                                    break;
                                case 4:
                                    soldEnergySort = "";
                                    avgPriceSort = "0";
                                    createDateSort = "";
                                    break;
                                case 5:
                                    soldEnergySort = "";
                                    avgPriceSort = "";
                                    createDateSort = "1";
                                    break;
                                case 6:
                                    soldEnergySort = "";
                                    avgPriceSort = "";
                                    createDateSort = "0";
                                    break;
                            }
                            refresh(true);

                        }
                    }))
                    .show();
        } else {
            orderPop.show();
        }


    }


    private void showChartByPop() {
        if (pop == null) {
            pop = (ChartLinSelectPop) new XPopup.Builder(getContext())
                    .hasShadowBg(true)
                    .popupAnimation(PopupAnimation.NoAnimation)
                    .atView(header_layout)
                    .asCustom(new ChartLinSelectPop(getContext(), new ChartLinSelectPop.OnClickListener() {
                        @Override
                        public void onPositiveClick(RatioCurveBean.Bean bean) {
                            tx_goods_right.setText(bean.getRatioName());
                            ratioId = bean.getRatioId();
                            refresh(true);

                        }
                    }))
                    .show();
        } else {
            pop.show();
        }


    }

    public void getChartList() {

        HttpRequestUtils.getInstance().request(new HashMap<>(), HttpInterConst.GET_RATIO_CURVE, new MvcNetCallback<RatioCurveBean>() {
            @Override
            public void onResponse(RatioCurveBean response, int id) {
                super.onResponse(response, id);
                if (null != response) {
                    if (null != response.getData() && response.getData().size() > 0) {
                        ratioName = response.getData().get(0).getRatioName();
                        ratioId = response.getData().get(0).getRatioId();
                        tx_goods_right.setText(ratioName);
                    } else {
                        ToastUtils.showShort(response.getMsg());
                    }
                    refresh(true);
                } else {
                    ToastUtils.showShort("曲线数据获取失败");
                }
            }
        });
    }


}
